! ==============================================================================
! This file is part of CUPP (Community Unified Physics Package) since 2023.
! ==============================================================================

module cupp_mesh_mod

  use cupp_const_mod

  implicit none

  type cupp_mesh_type
    integer :: id             = 0
    integer :: ncol           = 0
    integer :: nhalo          = 0
    integer :: ncol_with_halo = 0
    integer :: nlev           = 0
    integer :: max_ngb_size   = 0
    integer, allocatable :: ngb(:,:)
    real(r8), allocatable :: lon (:)
    real(r8), allocatable :: lat (:)
    real(r8), allocatable :: area(:)
  contains
    procedure :: init  => cupp_mesh_init
    procedure :: clear => cupp_mesh_clear
    final :: cupp_final
  end type cupp_mesh_type

contains

  subroutine cupp_mesh_init(this, ncol, nhalo, nlev, max_ngb_size)

    class(cupp_mesh_type), intent(inout) :: this
    integer, intent(in) :: ncol
    integer, intent(in) :: nhalo
    integer, intent(in) :: nlev
    integer, intent(in) :: max_ngb_size

    call this%clear()

    this%ncol           = ncol
    this%nhalo          = nhalo
    this%ncol_with_halo = ncol + nhalo
    this%nlev           = nlev
    this%max_ngb_size   = max_ngb_size

    allocate(this%ngb(this%max_ngb_size,this%ncol))

  end subroutine cupp_mesh_init

  subroutine cupp_mesh_clear(this)

    class(cupp_mesh_type), intent(inout) :: this

    if (allocated(this%ngb )) deallocate(this%ngb )
    if (allocated(this%lon )) deallocate(this%lon )
    if (allocated(this%lat )) deallocate(this%lat )
    if (allocated(this%area)) deallocate(this%area)

  end subroutine cupp_mesh_clear

  subroutine cupp_final(this)

    type(cupp_mesh_type), intent(inout) :: this

    call this%clear()

  end subroutine cupp_final

end module